﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuditModel;
using System.IO;
using LinqToExcel;
using LinqToExcel.Domain;
using LinqToExcel.Query;

namespace AuditWeb.Controllers
{ 
    public class CandidateQuotaController : Controller
    {
        private AuditDBEntities db = new AuditDBEntities();
        IAnnualEventBL iaebl = new AnnualEventBL();
        ICandidateQuotaBL icqbl = new CandidateQuotaBL();

        
        //Import quotas
        [HttpPost]
        [Authorize(Roles = "管理员")]
        public ActionResult Import(HttpPostedFileBase file)
        {
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            string importerror = "";

            ViewBag.AnnualEvent = currentevent;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = annualeventid;

            //upload file
            if (file!=null && file.ContentLength > 0)
            {
                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/temp"), fileName);
                file.SaveAs(path);
                //get data from file
                var excel = new ExcelQueryFactory(path);
                var candidatequotas = from cq in excel.Worksheet() select cq;
                //find each subject name
                var columnNames = excel.GetColumnNames("sheet1").ToArray();
                List<int> subjectids = new List<int>();
                for (int ci = 1; ci < columnNames.Count(); ci++)
                {
                    string subjectname = columnNames[ci];
                    if (string.IsNullOrEmpty(subjectname.Trim()))
                        break;
                    Subject subject = db.Subjects.SingleOrDefault(s => s.Name == subjectname);
                    if (subject == null)
                    {
                        importerror = string.Format("第{0}列学科组名称错误", ci.ToString());
                        return RedirectToAction("Index", new { error = importerror });
                    }
                    subjectids.Add(subject.Id);
                }
                //add candidatequota
                int count=candidatequotas.Count();
                if (count > 0)
                {
                    int i=1;
                    foreach(var cq in candidatequotas)
                    {
                        //var cq=candidatequotas.
                        //check and get county code
                        string countyname=cq[0].Value.ToString();//get countyname from excel cells
                        if (string.IsNullOrEmpty(countyname.Trim()))
                            break;
                        County county=db.Counties.SingleOrDefault(c=>c.Name==countyname);//check countycode
                        if(county==null)
                        {
                            importerror = string.Format("第{0}行区县名称错误", i.ToString());
                            return RedirectToAction("Index", new { error = importerror });
                        }
                        string countycode=county.Code;

                        //Add to subject one by one
                        for (int ci = 0; ci < subjectids.Count; ci++)
                        {
                            //check quota format
                            int quota = 0;
                            if (!int.TryParse(cq[ci+1].Value.ToString(), out quota))
                            {
                                importerror = string.Format("第{0}行{1}列名额数字错误", i.ToString(),ci.ToString());
                                return RedirectToAction("Index", new { error = importerror });
                            }

                            //create candidatequota object and add to db
                            CandidateQuota candidatequota = new CandidateQuota()
                            {
                                CountyCode = countycode,
                                AnnualEventID = annualeventid,
                                SubjectID = subjectids[ci],
                                Quota = quota
                            };

                            db.CandidateQuotas.AddObject(candidatequota);
                        }

                       
                        i++;
                    }
                }
                //save change
                try
                {
                    db.SaveChanges();
                }
                catch
                {
                    importerror = "数据重复错误";
                    return RedirectToAction("Index", new { error = importerror });
                }
            }
            else
            {
                importerror = "请选择文件!";
                 return RedirectToAction("Index", new { error = importerror });
            }


            return RedirectToAction("Index");
            
        }
        [Authorize(Roles = "管理员")]
        public ActionResult DeleteAll(string id)
        {
            AnnualEvent ae = iaebl.GetAnnualEvent(id);
            ViewBag.AnnualEvent = ae;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = id;
            return View(ae);
        }
        [Authorize(Roles = "管理员")]
        [HttpPost, ActionName("DeleteAll")]
        public ActionResult DeleteAllConfirmed(string id)
        {
            var cqlist = from cq in db.CandidateQuotas where cq.AnnualEventID == id select cq;
            foreach (CandidateQuota cq in cqlist)
            {
                db.CandidateQuotas.DeleteObject(cq);
            }
            db.SaveChanges();

            AnnualEvent ae = iaebl.GetAnnualEvent(id);
            ViewBag.AnnualEvent = ae;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = id;

            return RedirectToAction("Index");
        }
        
        //
        // GET: /CandidateQuota/
        [Authorize(Roles = "管理员")]
        public ViewResult Index(string countycode, string subjectid, string error )
        {
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;

            countycode = countycode == null ? "" : countycode.Trim();
            //check the county code of logged user
            if (User.IsInRole("区县管理员"))
                countycode = HttpContext.Profile["CountyCode"].ToString();

            int _subjectid;
            int.TryParse(subjectid, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            if (User.IsInRole("学科组组长"))
                _subjectid = (int)HttpContext.Profile["SubjectId"];

            var candidatequotas = icqbl.GetCandidateQuotas(annualeventid, _subjectid, countycode);// db.CandidateQuotas.Include("AnnualEvent");
            ViewBag.AnnualEvent = currentevent;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.ImportError = string.IsNullOrEmpty(error)?"":error;
            ViewBag.CountyCode = new SelectList(db.Counties.ToList(), "Code", "Name", countycode);
            ViewBag.SubjectId = new SelectList(db.Subjects.ToList(), "Id", "Name", _subjectid);
            return View(candidatequotas.ToList());
        }

        //
        // GET: /CandidateQuota/Details/5
        [Authorize(Roles = "管理员")]
        public ViewResult Details(string id)
        {
            CandidateQuota candidatequota = db.CandidateQuotas.Single(c => c.AnnualEventID == id);
            return View(candidatequota);
        }

        //
        // GET: /CandidateQuota/Create
        [Authorize(Roles = "管理员")]
        public ActionResult Create(string id)
        {
            string annualeventid = id;
            ViewBag.AnnualEventIDList = new SelectList(iaebl.GetActiveEvents(), "ID", "Title", annualeventid);
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name");
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name");
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(annualeventid);
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = annualeventid;
            return View();
        } 

        //
        // POST: /CandidateQuota/Create
        [Authorize(Roles = "管理员")]
        [HttpPost]
        public ActionResult Create(CandidateQuota candidatequota)
        {
            string eventid = candidatequota.AnnualEventID;
            if (ModelState.IsValid)
            {
                db.CandidateQuotas.AddObject(candidatequota);
                db.SaveChanges();
                return RedirectToAction("Index", new { id = eventid });  
            }

            ViewBag.AnnualEventIDList = new SelectList(iaebl.GetActiveEvents(), "ID", "Title", eventid);
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name");
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name");
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(eventid);
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = eventid;
            return View(candidatequota);
        }
        
        //
        // GET: /CandidateQuota/Edit/5
 [Authorize(Roles = "管理员")]
        public ActionResult Edit(string countycode,string annualeventid,string subjectid)
        {
            int i = int.Parse(subjectid);
            CandidateQuota candidatequota = db.CandidateQuotas.Single(c => c.AnnualEventID == annualeventid && c.SubjectID==i&&c.CountyCode==countycode);
            ViewBag.AnnualEventIDList = new SelectList(iaebl.GetActiveEvents(), "ID", "Title", candidatequota.AnnualEventID);
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name",candidatequota.SubjectID);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name",candidatequota.CountyCode);
            
            ViewBag.AnnualEvent = candidatequota.AnnualEvent;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = annualeventid;
            return View(candidatequota);
        }

        //
        // POST: /CandidateQuota/Edit/5
        [Authorize(Roles = "管理员")]
        [HttpPost]
        public ActionResult Edit(CandidateQuota candidatequota)
        {
            string eventid = candidatequota.AnnualEventID;
            if (ModelState.IsValid)
            {
                db.CandidateQuotas.Attach(candidatequota);
                db.ObjectStateManager.ChangeObjectState(candidatequota, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index", new { id = eventid });  
            }
            ViewBag.AnnualEventIDList = new SelectList(iaebl.GetActiveEvents(), "ID", "Title", candidatequota.AnnualEventID);
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", candidatequota.SubjectID);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", candidatequota.CountyCode);

            ViewBag.AnnualEvent = candidatequota.AnnualEvent;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = eventid;
            return View(candidatequota);
        }

        //
        // GET: /CandidateQuota/Delete/5
        [Authorize(Roles = "管理员")]
        public ActionResult Delete(string countycode, string annualeventid, string subjectid)
        {
            int i = int.Parse(subjectid);
            CandidateQuota candidatequota = db.CandidateQuotas.Single(c => c.AnnualEventID == annualeventid && c.SubjectID == i && c.CountyCode == countycode);
            ViewBag.AnnualEvent = candidatequota.AnnualEvent;
            ViewBag.SelectedIndex = "1";
            ViewBag.AnnualEventId = annualeventid;

            return View(candidatequota);
        }

        //
        // POST: /CandidateQuota/Delete/5
        [Authorize(Roles = "管理员")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string countycode, string annualeventid, string subjectid)
        {
            int i = int.Parse(subjectid);
            CandidateQuota candidatequota = db.CandidateQuotas.Single(c => c.AnnualEventID == annualeventid && c.SubjectID == i && c.CountyCode == countycode);
            db.CandidateQuotas.DeleteObject(candidatequota);
            db.SaveChanges();
            return RedirectToAction("Index", new {id = candidatequota.AnnualEventID });  
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}